package dao

import (
	"encoding/json"
	"gorm.io/gorm"
	"time"
)

type UserInfo struct {
	BaseModel
	UserNo      string `json:"userNo"`
	EnglishName string `json:"englishName"`
	RealName    string `json:"realName"`
	NickName    string `json:"nickName"`
	Cellphone   string `json:"cellPhone"`
	Gender      string
	Portrait    string
	UserType    string
	VipExpTime  BaseTime
	UserFlg     string
	UserTitle   string
	Birthday    BaseTime
	IdCardType  string
	IdCardNo    string
	Email       string
	QQ          string
	WxUnionId   string
	AddressId   string
	RegType     string
}

type UserDetail struct {
	UserId      string `json:"userId"`
	RealName    string `json:"realName"`
	RoleId      string `json:"roleId"`
	RoleName    string `json:"roleName"`
	CompanyId   string `json:"companyId"`
	CompanyName string `json:"companyName"`
}

func (u UserInfo) BeforeCreate(tx *gorm.DB) (err error) {
	err = u.CreateTime.Scan(time.Now())
	if err != nil {
		panic(err)
	}
	return
}

func (u *UserInfo) BeforeSave(tx *gorm.DB) (err error) {
	err = u.UpdateTime.Scan(time.Now())
	if err != nil {
		panic(err)
	}
	return
}

func (c *UserInfo) TableName() string {
	return "user_info"
}

func (c *UserInfo) ToJsonStr() string {
	marshal, err := json.Marshal(c)
	if err != nil {
		return ""
	}
	return string(marshal)
}

func SelectAllUserInfo() *[]UserInfo {
	info := []UserInfo{}
	DB.Where("is_del = ?", 0).Find(&info)
	return &info
}

func SelectUserInfoById(id int) *UserInfo {
	userInfo := UserInfo{}
	info := UserInfo{}
	info.ID = id
	info.IsDel = int(0)
	DB.Where(&info).First(&userInfo)
	return &userInfo
}

func FindUserInfoByExample(user *UserInfo) *[]UserInfo {
	info := []UserInfo{}
	DB.Where(&user)
	DB.Find(&info)
	return &info
}

func SaveUserInfo(user *UserInfo) int {
	DB.Create(&user)
	return user.ID
}

func SaveUserInfoBatch(users *[]UserInfo) {
	for _, info := range *users {
		DB.Create(&info)
	}
}

func UpdateUserInfo(user *UserInfo) {
	DB.Model(&user).Save(&user)
}

func DeleteUserInfoById(id int) {
	userInfo := UserInfo{}
	userInfo.ID = id
	DB.Delete(userInfo)
}

func DeleteUserInfoByExample(user *UserInfo) {
	DB.Where(&user).Delete(UserInfo{})
}

func FindUserDetail(userId int) *UserDetail {
	userDetail1 := UserDetail{}
	userDetail2 := UserDetail{}
	DB.Debug().Raw("select ui.id as user_id, ui.real_name as real_name,r.id as role_id, r.name as role_name from user_info ui left join role_user_relation rur on ui.id = rur.user_id left join role r on rur.role_id = r.id where ui.id = ?;", userId).Scan(&userDetail1)
	DB.Debug().Raw("select uo.company_id as company_id, o.name as company_name from user_info ui left join user_organization uo on ui.id = uo.user_id left join organization o on uo.organization_id = o.id where ui.id = ?;", userId).Scan(&userDetail2)
	userDetail1.CompanyId = userDetail2.CompanyId
	userDetail1.CompanyName = userDetail2.CompanyName
	return &userDetail1
}
